#include "timer.h"
#include "rtc.h"
#include <system/regs.h>
#include <interrupt/irq.h>
#include <task/task.h>
#include <system/mod.h>


uint32_t pit_tick = 0;

/*
 * La callback chiamata ad ogni interruzione
 */
static void timer_callback(regs_t *regs)
{
	// Mettere qui la funzione per il task switching
	task_switch();
	
	
	pit_tick++;
	
	if(pit_tick%100 == 0)
	{
		rtc_data.seconds++;
		if(rtc_data.seconds == 60)
		{
			rtc_data.seconds = 0;
			rtc_data.minutes++;
		}
		if(rtc_data.minutes == 60)
		{
			rtc_data.minutes = 0;
			rtc_data.hours++;
		}
	}
}


/*
 * Sleep for ms millisecondi
 * 1 s = 1000 ms
 */
void timer_sleep(uint32_t ms)
{
	uint32_t end = pit_tick + (ms / 10);
	for(pit_tick;pit_tick < end;);	
}

/*
 * Inizializza il timer
 */
uint32_t timer_init()
{
	uint32_t freq = TIMER_STANDARD_FREQ;
	uint32_t divisor;
	uint8_t l;
	uint8_t h;
	
	irq_install_handler(IRQ_TIMER, &timer_callback);

	divisor = 1193180 / freq;

	io_outb(0x43, 0x36);

	l = (uint8_t)(divisor & 0xFF);
	h = (uint8_t)((divisor>>8) & 0xFF );

	io_outb(0x40, l);
	io_outb(0x40, h);
}
 
 
 


uint32_t timer_get_tick()
{
	return pit_tick;	
}
